package server

import (
	"errors"
	"github.com/doujunyu/gogo/gogo_log"
	"github.com/doujunyu/gogo/sql_aid"
	"go_self/model"
	"go_self/util"
	"time"
)

// AttributeKeyByList 商品规格key列表
func AttributeKeyByList(input map[string]string) []map[string]interface{} {
	categorySql, args := sql_aid.PgTable(model.TableByAttributeKey).Field("id", "attribute_key_name").WhereRaw(func(query *sql_aid.PgQuery, i ...interface{}) {
		if i[0].(map[string]string)["attribute_key_id"] != "" { //是否热门
			query.Where("id = ?", i[0].(map[string]string)["attribute_key_id"])
		}
	}, input).OrderBy("id desc").PageSize(input["page"], input["page_size"]).ToSql()
	data, err := sql_aid.DataToMap(model.PgSql.Query(categorySql, args...))
	if err != nil || len(data) == 0 {
		return nil
	}
	//获取规格下的属性
	ids := util.ArrayField(&data, "id") //获取数据中的ID
	attributeValueSql, args := sql_aid.PgTable(model.TableByAttributeValue).Field("id", "attribute_key_id", "attribute_val_name").WhereIn("attribute_key_id", *ids...).ToSql()
	valdata, err := sql_aid.DataToMap(model.PgSql.Query(attributeValueSql, args...))
	attributeColumn := util.ArrayColumnGroupByInt64(&valdata, "attribute_key_id") //把attribute_key_id设置为数组下标
	for _, val := range data {                                                    //数据组装
		if attributeColumn[val["id"].(int64)] == nil {
			val["attributeValueArray"] = make([]map[string]interface{}, 0)
		} else {
			val["attributeValueArray"] = attributeColumn[val["id"].(int64)]
		}

	}
	return data
}

// AttributeKeyByAdd 商品规格key添加
func AttributeKeyByAdd(data map[string]interface{}) error {
	attributeKeySql, args := sql_aid.PgTable(model.TableByAttributeKey).InsertByMap(&data)
	_, err := model.PgSql.Exec(attributeKeySql, args...)
	if err != nil {
		gogo_log.Write("server_AttributeKeyByAdd", "商品规格key添加失败", err.Error())
		return errors.New("操作失败")
	}
	return nil
}

// AttributeKeyByEdit 商品规格key编辑
func AttributeKeyByEdit(input map[string]string) error {
	tx, err := model.PgSql.Begin()
	if err != nil {
		return errors.New("内部错误")
	}
	defer tx.Rollback()
	timestamp := time.Now().Format(time.RFC3339)
	update := make(map[string]interface{})
	update["attribute_key_name"] = input["attribute_key_name"]
	update["time_u"] = timestamp
	attributeKeySql, args := sql_aid.PgTable(model.TableByAttributeKey).Where("id = ?", input["attribute_key_id"]).UpdateByMap(&update)
	_, err = tx.Exec(attributeKeySql, args...)
	if err != nil {
		gogo_log.Write("server_AttributeKeyByEdit", "商品规格key编辑失败1", err.Error())
		return errors.New("操作失败")
	}
	//对应的属性值也要变
	attributeValueUpdate := make(map[string]interface{})
	attributeValueUpdate["attribute_key_name"] = input["attribute_key_name"]
	attributeValueSql, args := sql_aid.PgTable(model.TableByAttributeValue).Where("attribute_key_id = ?", input["attribute_key_id"]).UpdateByMap(&attributeValueUpdate)
	_, err = tx.Exec(attributeValueSql, args...)
	if err != nil {
		gogo_log.Write("server_AttributeKeyByEdit", "商品规格key编辑失败2", err.Error())
		return errors.New("操作失败")
	}
	tx.Commit()
	return nil
}

// AttributeKeyByDel 商品规格key删除
func AttributeKeyByDel(input map[string]string) error {
	attributeValSql, args := sql_aid.PgTable(model.TableByAttributeValue).Where("attribute_key_id = ?", input["attribute_key_id"]).ToSql()
	data, err := sql_aid.DataToMap(model.PgSql.Query(attributeValSql, args...))
	if err != nil || len(data) > 0 {
		return errors.New("当前规格不存在或规格下有没有删除的属性")
	}
	tx, _ := model.PgSql.Begin()
	defer tx.Rollback()
	attributeKeySql, args := sql_aid.PgTable(model.TableByAttributeKey).WhereId(input["attribute_key_id"]).Delete()
	_, err = tx.Exec(attributeKeySql, args...)
	if err != nil {
		gogo_log.Write("server_AttributeKeyByEdit", "商品规格key删除失败1", err.Error())
		return errors.New("规格删除失败")
	}
	attributeValueSql, args := sql_aid.PgTable(model.TableByAttributeValue).Where("attribute_key_id = ?", input["attribute_key_id"]).Delete()
	_, err = tx.Exec(attributeValueSql, args...)
	if err != nil {
		gogo_log.Write("server_AttributeKeyByEdit", "商品规格key删除失败2", err.Error())
		return errors.New("规格下属性删除失败")
	}
	tx.Commit()
	return nil
}

// AttributeValueByList 商品属性value列表
func AttributeValueByList(input map[string]string) []map[string]interface{} {
	attributeValueSql, args := sql_aid.PgTable(model.TableByAttributeValue).Field("id", "attribute_val_name").Where("attribute_key_id = ?", input["attribute_key_id"]).OrderBy("id desc").PageSize(input["page"], input["page_size"]).ToSql()
	data, _ := sql_aid.DataToMap(model.PgSql.Query(attributeValueSql, args...))
	return data
}

// AttributeValueByAdd 商品属性value添加
func AttributeValueByAdd(data map[string]interface{}) error {
	//查找规格key数据
	attributeKeySql, args := sql_aid.PgTable(model.TableByAttributeKey).WhereId(data["attribute_key_id"]).ToSql()
	attributeKeyData, err := sql_aid.DataToMap(model.PgSql.Query(attributeKeySql, args...))
	if err != nil || len(attributeKeyData) == 0 {
		return errors.New("规格key不存在")
	}
	//添加数据
	data["attribute_key_name"] = attributeKeyData[0]["attribute_key_name"].(string)
	attributeValueSql, args := sql_aid.PgTable(model.TableByAttributeValue).InsertByMap(&data)
	_, err = model.PgSql.Exec(attributeValueSql, args...)
	if err != nil {
		gogo_log.Write("server_AttributeValueByAdd", "商品属性value添加失败", err.Error())
		return errors.New("添加失败")
	}
	return nil
}

// AttributeValueByEdit 商品属性value编辑
func AttributeValueByEdit(input map[string]string) error {
	timestamp := time.Now().Format(time.RFC3339)
	update := make(map[string]interface{})
	update["attribute_val_name"] = input["attribute_val_name"]
	update["time_u"] = timestamp
	attributeValueSql, args := sql_aid.PgTable(model.TableByAttributeValue).Where("id = ?", input["attribute_val_id"]).UpdateByMap(&update)
	_, err := model.PgSql.Exec(attributeValueSql, args...)
	if err != nil {
		gogo_log.Write("server_AttributeValueByEdit", "商品属性value编辑失败", err.Error())
		return errors.New("编辑失败")
	}
	return nil
}

// AttributeValueByDel 商品属性value删除
func AttributeValueByDel(input map[string]string) error {
	attributeValueSql, args := sql_aid.PgTable(model.TableByAttributeValue).WhereId(input["attribute_val_id"]).Delete()
	_, err := model.PgSql.Exec(attributeValueSql, args...)
	if err != nil {
		gogo_log.Write("server_AttributeKeyByEdit", "商品属性value编辑失败", err.Error())
		return errors.New("删除失败")
	}
	return nil
}
